import axios from 'axios';
import Cookies from 'js-cookie'

axios.defaults.timeout = 5000;
// axios.defaults.baseURL = 'https://api.eheal.com.cn/medical-nutrition';
axios.defaults.headers = {
  'Content-Type': 'application/json'
}

// // 发送请求前处理request的数据
// axios.defaults.transformRequest = [function (data) {
//   // Do whatever you want to transform the data
//     let newData = ''
//     for (let k in data) {
//       newData += encodeURIComponent(k) + '=' + encodeURIComponent(data[k]) + '&'
//     }
//     return newData
// }];

//http request 拦截器
axios.interceptors.request.use(
  config => {
    const token = Cookies.get('authtoken'); // 注意使用的时候需要引入cookie方法，推荐js-cookie
    config.headers = {
      'authtoken': token
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);


//http response 拦截器
axios.interceptors.response.use(
  response => {
    //按需要加判断
    return response;
  },
  error => {
    return Promise.reject(error)
  }
)


/**
 * 封装get方法
 * @param url
 * @param data
 * @returns {Promise}
 */

export function fetch (url, params = {}) {
  return new Promise((resolve, reject) => {
    axios.get(url, {
      params: params
    })
      .then(response => {
        resolve(response.data);
      })
      .catch(err => {
        reject(err)
      })
  })
}

//上传图片
export function uploadImage (url, data) {
  return new Promise((resolve, reject) => {
    axios({
      url: url,
      method: 'post',
      data: data,
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Authorization': Cookies.get('token'),
      }
    }).then(response => {
      resolve(response.data);
    }).catch(err => {
      reject(err)
    })
  })
}

/**
 * 封装post请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function post (url, data = {}) {
  return new Promise((resolve, reject) => {
    axios.post(url, data)
      .then(response => {
        resolve(response.data);
      }, err => {
        reject(err)
      })
  })
}

/**
* 封装patch请求
* @param url
* @param data
* @returns {Promise}
*/

export function patch (url, data = {}) {
  return new Promise((resolve, reject) => {
    axios.patch(url, data)
      .then(response => {
        resolve(response.data);
      }, err => {
        reject(err)
      })
  })
}

/**
* 封装put请求
* @param url
* @param data
* @returns {Promise}
*/

export function put (url, data = {}) {
  return new Promise((resolve, reject) => {
    axios.put(url, data)
      .then(response => {
        resolve(response.data);
      }, err => {
        reject(err)
      })
  })
}